import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RequestContextService } from '../../auth/common/services/request-context.service';
import { RbacService } from '../rbac.service';
import { PERMISSIONS_KEY } from '../decorators/permissions.decorator';

/**
 * 权限守卫
 * 检查用户是否拥有所需权限（基于 CLS）
 */
@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private rbacService: RbacService,
    private requestContext: RequestContextService
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>(
      PERMISSIONS_KEY,
      [context.getHandler(), context.getClass()]
    );

    if (!requiredPermissions) {
      return true;
    }

    // 从 CLS 获取用户权限（由 JwtStrategy 在验证时设置）
    const userPermissions = this.requestContext.getCurrentUserPermissions();

    if (!userPermissions || userPermissions.length === 0) {
      return false;
    }

    return this.rbacService.hasPermission(userPermissions, requiredPermissions);
  }
}

